package com.generator.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.generator.page.Field;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author fengz
 * @version v1
 * @className Generator
 * @description TODO
 * @site glp.hcdlearning.com
 * @company 合得软件（上海）有限公司
 * @create 2019-07-16 14:50
 */
public class Generator {
    public static Map<String,Object> getParams(IntrospectedTable introspectedTable){
        Map<String,Object> params = new HashMap<>(16);
        String domainObjectName=introspectedTable.getFullyQualifiedTable().getDomainObjectName();
        String lowerDomainObjectName= StrUtil.lowerFirst(domainObjectName);
        String date= DateUtil.formatDate(new Date());
        String time= DateUtil.formatTime(new Date());
        params.put("domainObjectName",domainObjectName);
        params.put("lowerDomainObjectName",lowerDomainObjectName);
        params.put("date",date);
        params.put("time",time);

        List<Field> fields = introspectedTable.getAllColumns().stream().map(c->{
            Field field = new Field();
            field.name = c.getJavaProperty();
            field.upperName = StrUtil.upperFirst(field.name);
            field.columnName = c.getActualColumnName();
            return field;
        }).collect(Collectors.toList());
        params.put("fields",fields);
        return params;
    }

    static String rootPath="D:\\project\\java\\demo\\demo-web\\src\\main\\java";

    public static String getToolPath(String name){
        return StrUtil.format("{}\\com\\demo\\web\\generator\\tool\\\\{}Tool.java",rootPath,name);
    }
    public static String getToolImplPath(String name){
        return StrUtil.format("{}\\com\\demo\\web\\generator\\tool\\impl\\\\{}ToolImpl.java",rootPath,name);
    }

    public static String getParams(String name){
        return StrUtil.format("{}\\com\\demo\\web\\generator\\params\\\\{}\\Criterion.java",rootPath,StrUtil.lowerFirst(name));
    }
    public static String getReq(String name,String method){
        return StrUtil.format(
                "{}\\com\\demo\\web\\generator\\params\\\\{}\\req\\Req{}.java",
                rootPath,
                StrUtil.lowerFirst(name),
                StrUtil.upperFirst(method)
        );
    }
    static Configuration cfg;
    static {
        cfg = new Configuration(Configuration.VERSION_2_3_22);
        cfg.setClassForTemplateLoading(Generator.class,"/FreeMarker");
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    }
    public static void generatedJavaFile(IntrospectedTable introspectedTable,String templateName,String method){
        FullyQualifiedJavaType fullyQualifiedJavaType = new FullyQualifiedJavaType(
                StrUtil.format("com.baomidou.mybatisplus.core.mapper.BaseMapper<{}>",introspectedTable.getFullyQualifiedTable().getDomainObjectName())
        );
        Map<String,Object> params = Generator.getParams(introspectedTable);
        String domainObjectName = (String) params.get("domainObjectName");
        String path = null;
        switch (templateName){
            case "tool/Tool.java":
                path = Generator.getToolPath(domainObjectName);
                break;
            case "tool/impl/ToolImpl.java":
                path = Generator.getToolImplPath(domainObjectName);
                break;
            case "params/Criterion.java":
                path = Generator.getParams(domainObjectName);
                break;
            default:
                path = Generator.getReq(domainObjectName,method);
                break;
        }
        try (BufferedWriter outputStream= FileUtil.getWriter(path, Charset.forName("UTF-8"),false)){
            Template temp = cfg.getTemplate(templateName);
            temp.process(params, outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }
}
